// pages/friends/index.ts
import tran from "../../../utils/language";
import { handleImUserData, debounce } from "../../../utils/index.js";
import {
    userTargetInfo,
    contactBlacklist,
    deleteContactFriend,
    profilePhone,
    allFriendList,
} from "../../../utils/api.js";
Page({
    /**
     * 页面的初始数据
     */
    data: {
        _t: tran._t("friendList"),
        _tBase: tran._t("base"),
        token: getApp().globalData.token,
        showEventPopup: false,
        userData: [
            {
                userId: "324242",
                nickname: "Benjamin",
                avatarurl:
                    "https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg",
                status: 1, // 1在线 2忙碌 3离线
                personalityAvatar: "", // 性格的图片地址
                gender: 0,
            },
        ],
        allUserData: [
            {
                userId: "324242",
                nickname: "Benjamin",
                avatarurl:
                    "https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg",
                status: 1, // 1在线 2忙碌 3离线
                personalityAvatar: "", // 性格的图片地址
                gender: 0,
            },
        ],
        tapInfo: {
            userId: "",
        },
        homeFriendInfo: {},
        downPopupParams: {
            showDownPopup: false,
        },
        keyword: "",
        findFriendParams: {
            showDownPopup: false,
        },
        confirmPopup: {
            showPopup: false,
            topTitle: tran._t("base").topTitleTip,
            midText: tran._t("base").blockNameTip,
            confirmText: tran._t("base").confirmText,
            closeText: tran._t("base").closeBtnText,
        },
        delConfirmPopup: {
            showPopup: false,
            topTitle: tran._t("base").topTitleTip,
            midText: tran._t("base").delUserTip,
            confirmText: tran._t("base").confirmText,
            closeText: tran._t("base").closeBtnText,
        },
        filterData: [
            { text: "找个搭子一起玩", key: "321231", selectFlag: true },
            { text: "找个师父学点啥", key: "321431", selectFlag: false },
            { text: "找个朋友聊聊天", key: "3216431", selectFlag: false },
        ],
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
        this.setData({
            userData: [],
            allUserData: [],
        });
        this.getList();
    },

    toSelectPage(e: any) {
        const currentIndex = e.target.dataset.index;
        const { filterData } = this.data;
        filterData.length > 0 &&
            filterData.map((item: any, index: any) => {
                if (index === currentIndex) {
                    item.selectFlag = true;
                } else {
                    item.selectFlag = false;
                }
            });
        const userInfo = wx.getStorageSync("userInfo");
        if (userInfo && Object.keys(userInfo).length > 0 && userInfo.userId) {
            if (currentIndex == 0) {
                // 找个搭子一起玩
                wx.navigateTo({
                    url: "/pages/profile/findPartner/index",
                });
            } else if (currentIndex == 1) {
                // 找个师傅学点啥
                wx.navigateTo({
                    url: "/pages/profile/masterStudy/index",
                });
            } else if (currentIndex == 2) {
                // 找个朋友聊聊天
                wx.navigateTo({
                    url: "/pages/profile/findFriend/index",
                });
            }
        }
        this.setData({
            filterData,
        });
    },
    /**
     * 加入黑名单
     */
    joinBlackName() {
        const { confirmPopup } = this.data;
        confirmPopup.showPopup = true;
        this.setData({
            confirmPopup,
        });
        this.setData({
            showEventPopup: false,
        });
    },
    /**
     * 加入黑名单（我们这边的接口，得先调用im的加入黑名单接口后，再调用此接口）
     */
    joinBlack() {
        const { tapInfo } = this.data;
        console.log("黑名啊", tapInfo);
        const params = {
            tagetUserId: tapInfo.userId,
            flag: true, // true加入黑名单 false移除黑名单
        };
        contactBlacklist(params).then((res: any) => {
            wx.showToast({
                title: "操作成功",
            });
            this.setData({
                showEventPopup: false,
            });
            this.getList();
        });
    },
    /**
     * 点击解锁个人资料
     */
    openUnlockInfo() {
        this.handleProfilePhone(true);
    },
    // 取消解锁按钮
    closeUnlockInfo() {
        this.handleProfilePhone(false);
    },
    // 解锁/取消解锁个人资料接口调用
    handleProfilePhone(unlock: any) {
        const { tapInfo } = this.data;
        const params = {
            targetUserId: tapInfo.userId,
            unlock: unlock, // true解锁  false取消解锁
        };
        profilePhone(params).then((res) => {
            setTimeout(() => {
                wx.showToast({
                    title: "操作成功",
                });
            }, 100);
            // 调用查询
            this.getList();
            this.onClosePopup();
        });
    },
    closeFilterDownPopup() {
        const { findFriendParams } = this.data;
        findFriendParams.showDownPopup = false;
        this.setData({ findFriendParams: findFriendParams });
    },
    addTap() {
        const { findFriendParams } = this.data;
        findFriendParams.showDownPopup = true;
        this.setData({ findFriendParams: findFriendParams });
    },
    /**
     * 使用防抖
     */
    keywordChange: debounce(function (e: any) {
        let keyword = e[0].detail;
        if (keyword) {
            this.setData(
                {
                    keyword: keyword,
                },
                () => {
                    this.keyworkSearch();
                }
            );
        } else {
            this.setData({
                userData: this.data.allUserData,
            });
        }
    }, 300),
    keyworkSearch() {
        const { keyword, allUserData } = this.data;
        let list: any = [];
        allUserData.length > 0 &&
            allUserData.map((item: any) => {
                // 名字搜索，前端模糊查询
                if (item.nickname.indexOf(keyword) != -1) {
                    list.push(item);
                }
            });
        this.setData({
            userData: list,
        });
    },
    closeFriendInfoPopup() {
        const { downPopupParams } = this.data;
        downPopupParams.showDownPopup = false;
        this.setData({
            downPopupParams,
        });
    },
    closeDownPopup() {
        const { downPopupParams } = this.data;
        downPopupParams.showDownPopup = false;
        this.setData({ downPopupParams: downPopupParams });
    },
    /**
     * 点击解锁个人资料
     */
    goFriendInfo(e: any) {
        const info: any = e.currentTarget.dataset.info;
        this.setData({
            tapInfo: info,
        });
        const params = {
            targetUserId: info.userId,
        };
        userTargetInfo(params).then((res) => {
            const { downPopupParams } = this.data;
            downPopupParams.showDownPopup = true;
            this.setData({
                downPopupParams: downPopupParams,
                homeFriendInfo: res,
                showEventPopup: false,
            });
        });
    },
    goChat(e: any) {
        const { info } = e.currentTarget.dataset;
        wx.navigateTo({
            url: `/pages/profile/userChat/index?info=${JSON.stringify(info)}`,
        });
    },
    /**
     * 获取朋友列表
     */
    getList() {
        wx.showLoading({
            title: "加载中...",
        });
        allFriendList({}).then((res) => {
            if (res) {
                res.length > 0 &&
                    res.map((item: any) => {
                        item.nickname = item.pushName;
                        item.avatarurl = item.avatar;
                        item.puzzleUrl = item.personalityAvatar;
                    });
                this.setData({
                    userData: res || [],
                    allUserData: res || [],
                });
            } else {
                this.setData({
                    userData: [],
                    allUserData: [],
                });
            }
        });
        // wx.conn.getAllContacts().then((res: any) => {
        //   wx.hideLoading()
        //   this.getUserInfo(res.data)
        //   // this.setData({
        //   //   userData: res.data
        //   // })
        // })
        //   .catch((e) => {
        //     console.log(e, 'getAllContacts failed');
        //   });
    },
    /**
     * 获取用户属性
     * @param arr
     */
    getUserInfo(arr: any) {
        const userIds: any = [];
        arr.length > 0 &&
            arr.map((item: any) => {
                userIds.push(item.userId);
            });
        let userList: any = JSON.parse(JSON.stringify(userIds));
        wx.conn.fetchUserInfoById(userIds).then((res: any) => {
            const userInfoList = handleImUserData(userList, res.data);
            let list: any = [];
            userInfoList.length > 0 &&
                userInfoList.map((item: any) => {
                    const extData = item.ext ? JSON.parse(item.ext) : {};
                    item.puzzleUrl = extData.puzzleUrl;
                    const obj = {
                        ...item,
                        ...extData,
                    };
                    list.push(obj);
                });
            this.setData({
                userData: JSON.parse(JSON.stringify(list)),
                allUserData: JSON.parse(JSON.stringify(list)),
            });
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        // this.getList()
        if (typeof this.getTabBar === "function" && this.getTabBar()) {
            this.getTabBar().setData({
                activeKey: "friends",
            });
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {},
    /**
     * 接收消息监听
     */
    takeOverMsg() {
        const that = this;
        const loginInfo = wx.getStorageSync("userInfo");
        wx.conn.addEventHandler("eventName", {
            // 收到文本消息
            onTextMessage: function (message: any) {
                // 判断如果这条消息不是来自当前点击的用户，就不往下执行
                if (message.to !== loginInfo.userId) return;
                that.getList();
            },
            // 当前用户收到语音消息。
            onAudioMessage: function (message: any) {
                // 判断如果这条消息不是来自当前点击的用户，就不往下执行
                if (message.to !== loginInfo.userId) return;
                that.getList();
            },
            // 收到图片消息
            onImageMessage: function (message: any) {
                // 判断如果这条消息不是来自当前点击的用户，就不往下执行
                if (message.to !== loginInfo.userId) return;
                that.getList();
            },
            // 收到视频消息
            onVideoMessage: function (message: any) {
                // 判断如果这条消息不是来自当前点击的用户，就不往下执行
                if (message.to !== loginInfo.userId) return;
                that.getList();
            },
        });
    },
    confirmFn() {
        const { tapInfo } = this.data;
        // 调用 IM 的 API 将用户添加到黑名单
        wx.conn.addUsersToBlocklist({
            //可以添加单个用户 ID 或批量添加多个用户 ID 组成的数组。
            name: [tapInfo.userId],
        });
        this.joinBlack();
        this.closeFn();
        // setTimeout(() => {
        // }, 300)
    },
    delConfirmFn() {
        const { tapInfo, delConfirmPopup } = this.data;
        const that = this;
        // 调用 IM 的 API 删除好友
        let options = {
            // 会话 ID：单聊为对方的用户 ID，群聊为群组 ID。
            channel: tapInfo.userId,
            // 会话类型：（默认） `singleChat`：单聊；`groupChat`：群聊。
            chatType: "singleChat",
            // 删除会话时是否同时删除服务端漫游消息。
            // deleteRoam: true,
            deleteRoam: true,
        };
        wx.conn
            .deleteConversation(options)
            .then((res) => {
                console.log(res);
            })
            .catch((e) => {
                // 删除失败。
            });
        wx.conn.deleteContact(tapInfo.userId);
        setTimeout(() => {
            that.deleteFriendInt(tapInfo.userId);
        }, 500);
    },
    closeFn() {
        const { confirmPopup, delConfirmPopup } = this.data;
        confirmPopup.showPopup = false;
        delConfirmPopup.showPopup = false;
        this.setData({
            confirmPopup,
            delConfirmPopup,
        });
    },
    /**
     * 删除好友
     */
    deleteFriend() {
        const { tapInfo, delConfirmPopup } = this.data;
        this.onClosePopup();
        delConfirmPopup.showPopup = true;
        this.setData({
            delConfirmPopup,
        });
    },
    /**
     * 删除好友（先调用IM删除好友接口，再调此接口）
     */
    deleteFriendInt(targetUserId: string) {
        const params = {
            targetUserId: targetUserId,
        };
        deleteContactFriend(params).then((res: any) => {
            this.getList();
            this.closeFn();
        });
    },
    onClosePopup() {
        // const customPopup = this.selectComponent('#event-popup');
        // customPopup && customPopup.hidePopup()
        this.setData({
            showEventPopup: false,
        });
    },
    moreTap(e: any) {
        const info = e.currentTarget.dataset.info;
        this.setData({
            showEventPopup: true,
            tapInfo: info,
        });
    },
    methods: {},
});
